// 用户相关仓库
import { defineStore } from 'pinia';
import type {
    LoginFormData,
    LoginResponse,
    userInfoResponse,
} from '@/api/user/type';
import type { UserState } from './type/type';

// 引入操作本地存储的工作文件
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
import { constantRoutes } from '@/router/routes';
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index';
// 引入接口
const useUserStore = defineStore('user', {
    state: (): UserState => ({
        token: GET_TOKEN(),
        menuRoutes: constantRoutes,
        username: '',
        avatar: '',
    }),
    getters: {},
    actions: {
        // 登录并存储 token
        async userLogin(data: LoginFormData) {
            const res: LoginResponse = await reqLogin(data);
            if (res.code == 200) {
                this.token = res.data as string;
                // 本地存储
                SET_TOKEN(res.data as string);
                return 'ok';
            } else {
                return Promise.reject(new Error(res.message));
            }
        },
        // 获取用户信息
        async getUserInfo() {
            const res: userInfoResponse = await reqUserInfo();
            if (res.code == 200) {
                this.username = res.data.name;
                this.avatar = res.data.avatar;
                return 'ok';
            } else {
                return Promise.reject(new Error(res.message));
            }
        },
        // 退出登录
        async UserLogout() {
            const res = await reqLogout();
            if (res.code == '200') {
                // 清空数据并跳转登录页面
                this.username = '';
                this.avatar = '';
                this.token = '';
                REMOVE_TOKEN();
                return 'ok';
            } else {
                return Promise.reject(new Error(res.message));
            }
        },
    },
});
export default useUserStore;
